package com.frozenlab.android.weather.adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class WeatherDbAdapter {
	private static final String DATABASE_NAME = "weather.db";
    private static final String TABLE_NAME = "t_weather";
    
    /* Database table keys mapping */
    public static final String KEY_ROWID = "_id";
	public static final String KEY_NEIGHBORHOOD = "neighborhood";
	public static final String KEY_CITY = "city";
	public static final String KEY_CONDITION_TEXT = "condition_text";  
	public static final String KEY_TEMPERATURE = "temperature";  
	public static final String KEY_HIGH = "high";  
	public static final String KEY_LOW = "low";  
	public static final String KEY_LAST_UPDATED = "last_updated";  
	public static final String KEY_CONDITION_CODE = "condition_code"; 
    
    private static final String TAG = "WeatherDbAdapter";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        "create table " + TABLE_NAME + "(_id integer primary, " +
        " neigborhood text," +
        " city text," +
        " condition_text text," +
        " temperature text, " +
        " high text," +
        " low text," +
        " last_updated text," +
        " condition_code text);";


    private DatabaseHelper dbHelper;
    private SQLiteDatabase mDb;
    private final Context mCtx;
    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be opened/created
     * 
     * @param ctx the Context within which to work
     */
    public WeatherDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public WeatherDbAdapter open() throws SQLException {
    	dbHelper = new DatabaseHelper(mCtx);
        mDb = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
    	dbHelper.close();
    }

    public long createRecord(String name, String isBreakfast, String isLunch, String isDinner, String isSupper, 
    		String isRefreshment, String isOthers, String priceRange) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NEIGHBORHOOD, name);
        initialValues.put(KEY_CITY, isBreakfast);
        initialValues.put(KEY_CONDITION_TEXT, isLunch);
        initialValues.put(KEY_TEMPERATURE, isDinner);
        initialValues.put(KEY_HIGH, isSupper);
        initialValues.put(KEY_LOW, isRefreshment);
        initialValues.put(KEY_LAST_UPDATED, isOthers);
        initialValues.put(KEY_CONDITION_CODE, priceRange);

        return mDb.insert(TABLE_NAME, null, initialValues);
    }

    public boolean deleteRecord(long rowId) {

        return mDb.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor readAllRecords() {

        return mDb.query(TABLE_NAME, new String[] {
        		KEY_ROWID, 
        		KEY_NEIGHBORHOOD,
        		KEY_CITY,
        		KEY_CONDITION_TEXT,
        		KEY_TEMPERATURE,
        		KEY_HIGH,
        		KEY_LOW,
        		KEY_LAST_UPDATED,
        		KEY_CONDITION_CODE}, null, null, null, null, KEY_ROWID);
    }

    public Cursor readRecord(long rowId) throws SQLException {

        Cursor mCursor =
            mDb.query(true, TABLE_NAME, new String[] {
            		KEY_ROWID, 
            		KEY_NEIGHBORHOOD,
            		KEY_CITY,
            		KEY_CONDITION_TEXT,
            		KEY_TEMPERATURE,
            		KEY_HIGH,
            		KEY_LOW,
            		KEY_LAST_UPDATED,
            		KEY_CONDITION_CODE}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    public boolean updateRecord(long rowId, String neighborhood, String city, String conditionText, String temperature, String high, 
    		String low, String lastUpdated, String conditionCode) {
        ContentValues args = new ContentValues();
        args.put(KEY_NEIGHBORHOOD, neighborhood);
        args.put(KEY_CITY, city);
        args.put(KEY_CONDITION_TEXT, conditionText);
        args.put(KEY_TEMPERATURE, temperature);
        args.put(KEY_HIGH, high);
        args.put(KEY_LOW, low);
        args.put(KEY_LAST_UPDATED, lastUpdated);
        args.put(KEY_CONDITION_CODE, conditionCode);

        return mDb.update(TABLE_NAME, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
}
